<?php

namespace Models\Forms;

class FormAbstract {
    
    protected $_errors;
    
    public function isValid($data) {
        
        foreach ($this->_validateConfig as $elementName => $validators) {
            $value = isset($data[$elementName]) ? $data[$elementName] : null;
            
            foreach ($validators as $validator => $options) {
                $this->_validateElement($elementName, $value, $validator, $options);
            }
        }
        
        return empty($this->_errors);
    }

    
    public function getErrors() {
        return $this->_errors;
    }
    
    protected function _addError($elementName, $msg) {
        
        $this->_errors[$elementName][] = $msg;
    }
    
    protected function _validateElement($elementName, $value, $validator, $options) {
        $classValidator = '\Models\Validators\\' . $validator;

        if (!class_exists($classValidator)) {
            throw new \Exception('Cannot resolve validator name \'' . $validator . '\'');
        }
        
        $validatorInstance = new $classValidator($options);
        if (!$validatorInstance->isValid($elementName, $value)) {
            $this->_addError($elementName, $validatorInstance->getErrorMessage());
        }
    }
}
